package com.bysc.commentservice.utils;

import com.alibaba.fastjson.JSON;
import com.bysc.baseservice.config.RabbitmqConfig;
import com.bysc.commonutils.enums.CommentEnum;
import com.bysc.commonutils.enums.NoticeEnum;
import com.bysc.commonutils.message.NotificationMessage;
import com.bysc.commentservice.entity.vo.NoticeInnerClass;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

@Component
public class SendMessageService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发送收藏通知
     *
     * @param commentId 收藏的评论或帖子ID
     * @param userId    收藏用户ID
     * @param type      收藏类型
     * @param flag      0-点赞，1-收藏
     */
    public void doNotice(String commentId, String userId, CommentEnum type, String flag) {
        NoticeEnum noticeType = NoticeEnum.LIKE;//点赞通知
        // 构建通知消息
        if ("1".equals(flag)) {
            noticeType = NoticeEnum.COLLECT;//收藏通知
        }

        String collect = "";
        switch (type) {
            case POST: {
                collect = "post";
                break;
            }
            case PARENT: {
                collect = "comment";
                break;
            }
            case SON: {
                collect = "sonComment";
                break;
            }
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(commentId));
        query.fields().include("userId");
        NoticeInnerClass noticeInnerClass = mongoTemplate.findOne(query, NoticeInnerClass.class, collect);
        String noticedUserId = noticeInnerClass.getUserId();// 获取被通知人id
        NotificationMessage notificationMessage = new NotificationMessage(userId, noticedUserId, commentId, "", type, noticeType);
        if (notificationMessage.getNoticedUserId().equals(userId)) {
            return;//自己收藏自己不通知
        }
        String message = JSON.toJSONString(notificationMessage);
        // 发送到RabbitMQ
        try {
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS_INFORM, "inform.notice", message);
        } catch (AmqpException e) {
            throw new RuntimeException(e);
        }
    }
}
